package com.gregbugaj.gps;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Longitude {


	private double degrees;
	private double minutes;
	private double seconds;
	private Direction direction;

	private static NumberFormat format=DecimalFormat.getInstance();
	static{
		format.setMaximumFractionDigits(6);
	}
	private double decimal;
	public Longitude(String value, Direction direction){
		if(Direction.NORTH.equals(direction) ||Direction.SOUTH.equals(direction)){
			throw  new IllegalArgumentException("Longitude can only be WEST or EAST");
		}
		this.direction=direction;
		String[] parts=value.split("\\.");
		degrees=Double.parseDouble(parts[0].substring(0, parts[0].length()-2));
		minutes=Double.parseDouble(parts[0].substring(parts[0].length()-2, parts[0].length()));
		seconds=Double.parseDouble(parts[1].substring(parts[1].length()-2, parts[1].length()));

		int sign=Direction.EAST.equals(direction)?1:-1;
		// Decimal Degrees = Degrees + minutes/60 + seconds/3600
		decimal=(degrees+(minutes/60)+(seconds/3600) )* sign;
		decimal=Double.parseDouble(format.format(decimal));
	}

	/**
	 * Create Latitude from decimal value
	 * @param decimalValue
	 */
	public Longitude(double decimalValue){
		decimal=decimalValue;
		if(decimalValue<0){
			degrees=Math.ceil(decimal);
			direction=Direction.WEST;
		}
		else{
			degrees=Math.floor(decimal);
			direction=Direction.EAST;
		}
		double remMin=(decimalValue-degrees)*60;
		if(remMin<-0){
			remMin*=-1;
		}

		minutes=Math.floor(remMin);
		seconds=Math.round((remMin-minutes)*60);
	}
	
	
	public  double getDecimal(){
		return decimal;
	}

	public void setDegrees(double degrees) {
		this.degrees = degrees;
	}
	public double getMinutes() {
		return minutes;
	}
	public void setMinutes(double minutes) {
		this.minutes = minutes;
	}
	public double getSeconds() {
		return seconds;
	}
	public void setSeconds(double seconds) {
		this.seconds = seconds;
	}
	public Direction getDirection() {
		return direction;
	}
	public void setDirection(Direction direction) {
		this.direction = direction;
	}

	public boolean equals(Longitude that) {
		
		return this.getDecimal()==that.getDecimal();
	}
	
	@Override
	public String toString() {
		return "["+degrees+", "+minutes+", "+seconds+", "+ direction +", dec="+getDecimal()+"]";
	}

	public double getDegrees() {
		return degrees;
	}
}
